package hongcaosp.app.android.video.player;

import android.content.Context;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import hongcaosp.app.android.R;
import xlj.lib.android.base.view.recyclepager.OnItemVisibleListener;
import xlj.lib.android.base.view.recyclepager.PagerLayoutManager;

public class PagerPlayerManager {
//    private VideoProxy playVideo;
//    private VideoHolder videoHolder;
    private RecyclerView recyclerView;
    private Context context;
    private int currentSelect;

    public PagerPlayerManager(RecyclerView recyclerView, Context context) {
        this.recyclerView = recyclerView;
        this.context = context;
        PagerLayoutManager mLayoutManager = new PagerLayoutManager(context, OrientationHelper.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
        mLayoutManager.setOnViewPagerListener(new OnItemVisibleListener() {
            @Override
            public void onItemInit(int position, View view) {
            }

            @Override
            public void onItemRelease(boolean isNext, int position, View view) {
                releaseVideo(view);
            }

            @Override
            public void onItemSelected(int position, boolean isBottom, View view) {
                playVideo(position, view);
                currentSelect = position;
            }
        });
    }

    public int getCurrentSelect() {
        return currentSelect;
    }

    /**
     * 播放视频
     */
    private void playVideo(int position, View view) {
        Log.i("PagerPlaye","playVideo index" + position);
        if (view != null) {
            VideoHolder nextVideo = (VideoHolder) recyclerView.findViewHolderForLayoutPosition(position);
            nextVideo.freshUserFlag();
            nextVideo.playVideo();
        }
    }

    public void release() {
//        if (playVideo != null) {
//            playVideo.release();
//        }
    }

    /**
     * 停止播放
     */
    public void releaseVideo(View view) {
        if (view != null) {
            SimplePlayerView videoView = view.findViewById(R.id.player);
            videoView.resetPlayer();
            videoView.release();
        }
    }
}
